import { Component, OnInit } from '@angular/core';
import { Input, Output, EventEmitter } from '@angular/core';
import { OnChanges, SimpleChanges } from '@angular/core';


@Component({
  selector: 'app-stars',
  templateUrl: './stars.component.html',
  styleUrls: ['./stars.component.css']
})
export class StarsComponent implements OnInit, OnChanges {
 @Input()
 private rating:number = 0;//从父级传过来
 @Output() //使数据双向绑定，子组件的数据变化了也能影响父组件中相应值的变化
 private ratingChange: EventEmitter<number> = new EventEmitter();
 private stars:Array<boolean>
 @Input()
 private readonly = true;
  constructor() { }

  ngOnInit() {

  }
  //将原来在init中的语句放到changes事件更好，rating具有输入属性，每次改变时，都会触发changes事件。
  //我们需要的又是stars数组和rating一起变化，所以语句放在这个函数里更好
  ngOnChanges(changes: SimpleChanges) {
    this.stars=[];
    for(let i=1; i<6; i++) {
      this.stars.push(i > this.rating);
    }
  }
  // 点击修改rating值
  clickStar(index: number) {
    if(!this.readonly) {
      this.rating = index * 1 + 1;
     // this.ngOnInit();//修改了rating值，还要修改starts数组才行
      this.ratingChange.emit(this.rating);
    }
  }

}
